<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="eqName">
        <el-input
          v-model="queryParams.eqName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入设备型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="useStatus">
        <el-select
          v-model="queryParams.useStatus"
          placeholder="请选择使用状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.USE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="testStatus">
        <el-select
          v-model="queryParams.testStatus"
          placeholder="请选择设备状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TEST_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['testequipment:test-equipment:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['testequipment:test-equipment:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['testequipment:test-equipment:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="eqName" />
      <el-table-column label="所属部门" align="center" prop="deptId">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DEPT" :value="scope.row.deptId" />
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="model" />
      <el-table-column label="存放位置" align="center" prop="storageLocation" />
      <el-table-column label="使用状态" align="center" prop="useStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.USE_STATUS" :value="scope.row.useStatus" />
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="testStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TEST_STATUS" :value="scope.row.testStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column
        label="创建时间（入场时间）"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="300px">
        <template #default="scope">
          <el-button
            link
            @click="handleView(scope.row)"
            v-hasPermi="['testequipment:test-equipment:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['testequipment:test-equipment:update']"
          >
            编辑
          </el-button>
          
         <!-- 设备状态按钮（优化后逻辑） -->
        <!-- 1. 未试验状态：显示可用的申请试验按钮 -->
        <el-button
          link
          type="success"
          v-if="scope.row.testStatus === 0"
          @click="handleApplyTest(scope.row)"
          v-hasPermi="['testequipment:test-equipment:update']"
        >
          申请试验
        </el-button>
        <!-- 2. 试验中状态：显示试验结果按钮 -->
        <el-button
          link
          type="warning"
          v-else-if="scope.row.testStatus === 1"
          @click="openTestResultDialog(scope.row)"
          v-hasPermi="['testequipment:test-equipment:update']"
        >
          试验结果
        </el-button>
        <!-- 3. 试验完成且失败：显示可用的重新申请试验按钮 -->
        <el-button
          link
          type="success"
          v-else-if="scope.row.testStatus === 2 && scope.row.testResult === '失败'"
          @click="handleApplyTest(scope.row)"
          v-hasPermi="['testequipment:test-equipment:update']"
        >
          重新申请试验
        </el-button>
        <!-- 4. 试验完成且成功：显示灰色的申请试验按钮（不可用） -->
        <el-button
          link
          disabled
          v-else-if="scope.row.testStatus === 2 && scope.row.testResult === '成功'"
          v-hasPermi="['testequipment:test-equipment:update']"
        >
          申请试验
        </el-button>
        <!-- 出库按钮：仅当试验成功且未出库时可点击（优化判断逻辑） -->
        <el-button
          link
          type="info"
          @click="handleOutStorage(scope.row)"
          :disabled="!(scope.row.testStatus === 2 && scope.row.testResult === '成功' && scope.row.useStatus === 0)"
          v-hasPermi="['testequipment:test-equipment:update']"
        >
          出库
        </el-button>
        <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['testequipment:test-equipment:delete']"
          >
            删除
          </el-button>
          
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TestEquipmentForm ref="formRef" @success="getList" />

  <!-- 试验结果弹窗（新增完整组件） -->
  <el-dialog
    v-model="testResultDialogVisible"
    title="试验结果录入"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="testResultFormRef"
      :model="testResultForm"
      label-width="80px"
      :rules="{
        testResult: [{ required: true, message: '请选择试验结果', trigger: 'change' }]
      }"
    >
      <el-form-item label="试验结果" prop="testResult">
        <el-select
          v-model="testResultForm.testResult"
          placeholder="请选择试验结果"
          class="w-full"
        >
          <el-option label="成功" value="成功" />
          <el-option label="失败" value="失败" />
        </el-select>
      </el-form-item>
      <el-form-item label="试验附件">
        <el-upload
          action="/api/upload"
          :file-list="testResultForm.fileList"
          :on-success="handleFileUploadSuccess"
          :on-remove="handleFileRemove"
          multiple
          accept=".pdf,.doc,.docx,.jpg,.png"
          list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="text-xs text-gray-500 mt-2">支持上传PDF、Word、图片格式文件，最多上传5个</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="testResultDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmTestResult">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ElMessageBox, ElMessage } from 'element-plus'
import { TestEquipmentApi, TestEquipment } from '@/api/testequipment/testequipment'
import TestEquipmentForm from './TestEquipmentForm.vue'
import { TestEquipmentUseApi } from '@/api/testequipmentuse/testequipmentuse'
import type { UploadFile } from 'element-plus'

/** 参试设备管理表 列表 */
defineOptions({ name: 'TestEquipment' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 列表相关状态
const loading = ref(true)
const list = ref<TestEquipment[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  eqName: undefined,
  model: undefined,
  useStatus: undefined,
  testStatus: undefined,
})
const queryFormRef = ref()
const exportLoading = ref(false)
const currentRow = ref<TestEquipment>({})

// 批量删除相关
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: TestEquipment[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

// 试验结果弹窗相关状态（新增）
const testResultDialogVisible = ref(false)
const testResultFormRef = ref()
const currentTestRow = ref<TestEquipment>({}) // 存储当前操作的设备行数据
const testResultForm = reactive({
  testResult: '', // 试验结果：成功/失败
  fileList: [] as UploadFile[], // 上传的附件列表
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TestEquipmentApi.getTestEquipmentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 查看按钮操作 */
const handleView = async (row: TestEquipment) => {
  try {
    const detail = await TestEquipmentApi.getTestEquipment(row.id!)
    let detailHtml = '<div style="white-space: pre-line;">';
    detailHtml += `设备详情：\n`;
    detailHtml += `编号：${detail.id}\n`;
    detailHtml += `设备名称：${detail.eqName || '-'}\n`;
    detailHtml += `所属部门：${getIntDictOptions(DICT_TYPE.DEPT).find(d => d.value === detail.deptId)?.label || '-'}\n`;
    detailHtml += `设备型号：${detail.model || '-'}\n`;
    detailHtml += `存放位置：${detail.storageLocation || '-'}\n`;
    detailHtml += `使用状态：${getIntDictOptions(DICT_TYPE.USE_STATUS).find(d => d.value === detail.useStatus)?.label || '-'}\n`;
    detailHtml += `设备状态：${getIntDictOptions(DICT_TYPE.TEST_STATUS).find(d => d.value === detail.testStatus)?.label || '-'}\n`;
    detailHtml += `创建人：${detail.creator || '-'}\n`;
    detailHtml += `创建时间（入场时间）：${detail.createTime ? dateFormatter(detail.createTime) : '-'}`;
    detailHtml += '</div>';
    
    ElMessageBox.alert(detailHtml, '设备详情', {
      confirmButtonText: '确定',
      type: 'info',
      dangerouslyUseHTMLString: true
    })
  } catch (error) {
    message.error('获取设备详情失败')
  }
}

/** 申请试验按钮操作 */
const handleApplyTest = async (row: TestEquipment) => {
  try {
    await ElMessageBox.confirm('确定要申请试验吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 构建完整的更新参数，确保所有必填字段都正确传递
    const updateParams = {
      id: row.id,
      eqName: row.eqName, // 确保设备名称存在
      testStatus: 1, // 试验中状态
      
      // 提供其他必要字段的默认值，避免参数缺失
      model: row.model || '',
      deptId: row.deptId || 0,
      storageLocation: row.storageLocation || '',
      useStatus: row.useStatus || 0,
      warehouseId: row.warehouseId || 0,
      
      // 保留其他可能需要的字段
      ...(row.creator ? { creator: row.creator } : {}),
      ...(row.createTime ? { createTime: row.createTime } : {})
    }
    
    await TestEquipmentApi.updateTestEquipment(updateParams)
    message.success('申请试验成功')
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('申请试验失败:', error)
      message.error('申请试验失败')
    }
  }
}

/** 打开试验结果弹窗（新增） */
const openTestResultDialog = (row: TestEquipment) => {
  currentTestRow.value = row // 存储当前设备数据
  // 重置表单
  testResultForm.testResult = ''
  testResultForm.fileList = []
  testResultDialogVisible.value = true
}

/** 附件上传成功回调（新增） */
const handleFileUploadSuccess = (response: any, file: UploadFile) => {
  // 假设后端返回格式：{ code: 200, data: { url: '文件地址' } }
  if (response.code === 200) {
    file.url = response.data.url
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}

/** 附件移除回调（新增） */
const handleFileRemove = (file: UploadFile) => {
  const index = testResultForm.fileList.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    testResultForm.fileList.splice(index, 1)
  }
}

/** 确认试验结果（核心修正逻辑） */
const confirmTestResult = async () => {
  try {
    // 表单校验
    await testResultFormRef.value.validate()
    
    const { testResult, fileList } = testResultForm
    // 处理附件地址（拼接多个文件地址）
    const testAttachmentUrl = fileList.map(file => file.url).filter(Boolean).join(',')
    
    // 构造更新参数，确保所有必填字段都正确传递
    const updateData = {
      id: currentTestRow.value.id,
      eqName: currentTestRow.value.eqName, // 确保设备名称存在
      testStatus: 2, // 试验完成状态
      testResult,    // 试验结果
      testAttachmentUrl, // 附件地址
      
      // 提供其他必要字段的默认值，避免参数缺失
      model: currentTestRow.value.model || '',
      deptId: currentTestRow.value.deptId || 0,
      storageLocation: currentTestRow.value.storageLocation || '',
      useStatus: currentTestRow.value.useStatus || 0,
      warehouseId: currentTestRow.value.warehouseId || 0,
      
      // 保留其他可能需要的字段
      ...(currentTestRow.value.creator ? { creator: currentTestRow.value.creator } : {}),
      ...(currentTestRow.value.createTime ? { createTime: currentTestRow.value.createTime } : {})
    }
    
    console.log('更新试验结果参数:', updateData)
    
    // 调用更新接口
    const response = await TestEquipmentApi.updateTestEquipment(updateData)
    console.log('试验结果更新成功，后端返回:', response)
    
    // 提示信息
    const resultMsg = testResult === '成功' ? '试验成功，可进行出库操作' : '试验失败，可重新申请试验'
    message.success(`试验结果录入成功！${resultMsg}`)
    
    // 关闭弹窗+刷新列表
    testResultDialogVisible.value = false
    await getList()
  } catch (error: any) {
    console.error('试验结果更新失败:', error)
    if (error.name === 'ValidationError') {
      // 表单校验失败，已自动提示
      return
    }
    message.error('试验结果更新失败：' + (error.response?.data?.msg || '服务器异常'))
  }
}

/** 出库按钮操作 */
const handleOutStorage = async (row: TestEquipment) => {
  try {
    await ElMessageBox.confirm('确定要出库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 1. 更新设备使用状态为已出库
    await TestEquipmentApi.updateTestEquipment({
      id: row.id,
      useStatus: 1, // 已出库
      // 补充必填字段（从当前行数据中获取，确保非空）
      eqName: row.eqName, // 设备名称（必填）
      deptId: row.deptId, // 所属部门（必填）
      model: row.model, // 设备型号（必填）
      warehouseId: row.warehouseId, // 存放库房id（核心必填项，之前缺失）
      storageLocation: row.storageLocation, // 存放位置（必填）
      testStatus: row.testStatus, // 设备状态（必填）
    })
    
    // 2. 新增出库记录
    await TestEquipmentUseApi.createTestEquipmentUse({
      eqId: row.id,
      operationType: 1, // 1-出库
      operationTime: new Date(),
      remark: `设备${row.eqName}（ID:${row.id}）试验成功后出库`
    })
    
    message.success('出库成功，已记录使用记录')
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('出库失败:', error)
      message.error('出库失败')
    }
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await TestEquipmentApi.deleteTestEquipment(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 批量删除 */
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await TestEquipmentApi.deleteTestEquipmentList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await TestEquipmentApi.exportTestEquipment(queryParams)
    download.excel(data, '参试设备管理表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 可选：调整上传组件样式 */
::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}
</style>